package com.yeyks.task;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.common.collect.Maps;
//import com.xxl.job.core.biz.model.ReturnT;
//import com.xxl.job.core.handler.IJobHandler;
//import com.xxl.job.core.handler.annotation.JobHandler;
import com.yeyks.common.constants.MessageTemplate;
import com.yeyks.common.constants.consumer.UserInviteRelationTypeConstant;
import com.yeyks.common.dto.AccountCardDTO;
import com.yeyks.common.dto.ZeroParentRate;
import com.yeyks.common.em.OrderStatusEnum;
import com.yeyks.common.em.UserBillType;
import com.yeyks.common.em.card.MemberCardTypeEnum;
import com.yeyks.common.em.vip.HotelDeveloperRelationTypeEnum;
import com.yeyks.common.em.vip.MiniVipCommissionBillTypeEnum;
import com.yeyks.common.em.vip.VipCommissionBillTypeEnum;
import com.yeyks.common.exception.ServiceException;
import com.yeyks.common.utils.DateUtils;
import com.yeyks.common.utils.FormatUtils;
import com.yeyks.commonReference.service.config.ConfigService;
import com.yeyks.commonReference.service.consumer.MemberCardService;
import com.yeyks.commonReference.service.consumer.MessageNoticeTemplateService;
import com.yeyks.commonReference.service.hotel.HotelAccountBillService;
import com.yeyks.commonReference.service.hotel.HotelDeveloperRelationService;
import com.yeyks.commonReference.service.hotel.HotelInfoService;
import com.yeyks.commonReference.service.order.OrderHeadService;
import com.yeyks.commonReference.service.vip.AccountVipSalerRelationService;
import com.yeyks.commonReference.service.vip.MiniVipCommissionBillService;
import com.yeyks.commonReference.service.vip.VipCommissionBillService;
import com.yeyks.commonReference.service.vip.VipCommissionRateConfigService;
import com.yeyks.consumer.dal.domain.MemberCard;
import com.yeyks.consumer.dal.domain.MessageNotice;
import com.yeyks.consumer.service.MessageNoticeService;
import com.yeyks.consumer.service.UserAccountOverviewService;
import com.yeyks.consumer.service.UserInviteRelationService;
import com.yeyks.hotel.dal.domain.HotelDeveloperRelation;
import com.yeyks.order.dal.domain.OrderHead;
import com.yeyks.vip.dal.domain.AccountVipSalerRelation;
import com.yeyks.vip.dal.domain.VipCommissionRateConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author shuai
 * @date 2019/10/28 13:28
 */
//@Component
//@Slf4j
//@JobHandler(value = "orderCompleteTask")
//public class OrderCompleteTask extends IJobHandler {
public class OrderCompleteTask {
//    @Autowired
//    private OrderHeadService orderHeadService;
//    @Autowired
//    private ConfigService configService;
//    @Autowired
//    private HotelAccountBillService hotelAccountBillService;
//    @Autowired
//    private HotelInfoService hotelInfoService;
//    @Autowired
//    private VipCommissionBillService vipCommissionBillService;
//    @Autowired
//    private MemberCardService memberCardService;
//    @Autowired
//    private VipCommissionRateConfigService vipCommissionRateConfigService;
//    @Autowired
//    private HotelDeveloperRelationService hotelDeveloperRelationService;
//    @Autowired
//    private AccountVipSalerRelationService accountVipSalerRelationService;
//    @Autowired
//    private MiniVipCommissionBillService miniVipCommissionBillService;
//    @Autowired
//    private UserInviteRelationService userInviteRelationService;
//    @Autowired
//    private UserAccountOverviewService userAccountOverviewService;
//    @Autowired
//    private MessageNoticeTemplateService messageNoticeTemplateService;
//    @Autowired
//    private MessageNoticeService messageNoticeService;

//    @Override
//    public ReturnT<String> execute(String param) {
//        orderComplete();
//        return SUCCESS;
//    }

//    @Scheduled(cron = "${schedule.order.checkOut}")
//    public void orderComplete() {
//        log.info("订单完成执行，time = {}", DateUtil.formatDateTime(new Date()));
//        //查询出来所有待入住和待退款和入住中的订单（2,5,7）
//        List<OrderHead> orderHeads = orderHeadService.list(new QueryWrapper<OrderHead>()
//                .in(OrderHead.STATUS, OrderStatusEnum.PRECHECKIN.value(), OrderStatusEnum.LIVING.value()));
//        if (orderHeads == null || orderHeads.size() == 0) {
//            log.info("查询到的所有待入住和待退款和入住中的订单数为空");
//            return;
//        }
//        Date nowDate = new Date();
//        //过滤离店时间后12个小时小于当前时间的订单
//        List<OrderHead> disposeOrderHeads = orderHeads.stream().filter(e -> DateUtils.dateCompareDate(nowDate, DateUtils.afterHoursToDate(e.getCheckOut(), 12L))).collect(Collectors.toList());
//        if (disposeOrderHeads.size() == 0) {
//            log.info("需要处理的订单数为空");
//            return;
//        }
//        for (OrderHead orderHead : disposeOrderHeads) {
//            orderHead.setStatus(OrderStatusEnum.POSTCHECKOUT.value());
//            if (orderHeadService.update(null, new UpdateWrapper<OrderHead>()
//                    .set(OrderHead.SNAPSHOT_REFUND_FEE, null)
//                    .set(OrderHead.STATUS, OrderStatusEnum.POSTCHECKOUT.value())
//                    .eq(OrderHead.ORDER_NO, orderHead.getOrderNo()))) {
//                log.info("修改订单状态为已完成成功{}", orderHead.getOrderNo());
//                //c2b和b2c订单给该下单用户的上级以及上上级分钱
//                if (orderHead.getVipFlag() == 0 || orderHead.getVipFlag() == 2) {
//                    setCommissionUserParent(orderHead);
//                }
//                //vip订单佣金入账
////                if (orderHead.getVipFlag() == 1 && "yyks".equals(orderHead.getSourceType())) {
////                    setCommission(orderHead);
////                }
//                else if (orderHead.getVipFlag() == 3 && "yyks".equals(orderHead.getSourceType())) {
//                    //精选订单佣金入账
//                    setMiniVipCommission(orderHead);
//                } else {//c2b的话判断是否是第一单(设置免佣期使用)
//                    int count = orderHeadService.orderCount(orderHead.getHotelId(), orderHead.getVipFlag(), 3);
//                    if (1 == count) {
//                        hotelInfoService.setNoFeeDateAtFirstOrder(orderHead.getHotelId(), orderHead.getGmtCreate());
//                    }
//                }
//            } else {
//                log.error("修改订单状态为已完成失败{}", orderHead.getOrderNo());
//            }
//        }
//        //过滤掉甄选酒店的单和小于某个点的单，写入酒店订单账户信息
//        Date overTime = configService.getHotelDate();
//        List<OrderHead> c2bOrders = disposeOrderHeads.stream().filter(e -> (e.getVipFlag() == 0 || e.getVipFlag() == 2) && "yyks".equals(e.getSourceType()) && DateUtils.dateCompareDate(DateUtils.afterHoursToDate(e.getCheckOut(), 12L), overTime)).collect(Collectors.toList());
//        if (!hotelAccountBillService.insertHotelAccountBill(c2bOrders)) {
//            log.info("写入酒店订单账户信息失败");
//        }
//        log.info("订单完成执行end");
//    }
//
//
//    /**
//     * c2b和b2c订单上级发放佣金
//     *
//     * @param orderHead 订单
//     */
//    private void setCommissionUserParent(OrderHead orderHead) {
//        try {
//            ZeroParentRate zeroParentRate = configService.getZeroRate();
//            //查询该订单用户的上级(0元邀请)
//            Integer parentId = userInviteRelationService.selectParentIdByUserId(orderHead.getUserId(), 1);
//            if (null == parentId) {
//                log.info("该用户不存在上级orderHead中的userId = {}", orderHead.getUserId());
//                return;
//            }
//            //给上级发佣金
//            Integer parentAmount = FormatUtils.amountToRateV2(orderHead.getSnapshotOriginTotalFee(), zeroParentRate.getParentRate());
//            userAccountOverviewService.addAmount(parentAmount, parentId, UserBillType.ZERO_PROFIT.value(), UserBillType.ZERO_PROFIT.desc(), UserInviteRelationTypeConstant.INVITE_ZERO);
//            //写入佣金通知
//            messageNotice(parentId, parentAmount, true);
//            //查询该订单用户上级的上级(0元邀请)
//            Integer parentParentId = userInviteRelationService.selectParentIdByUserId(parentId, 1);
//            if (null == parentParentId) {
//                log.info("该用户不存在上级的上级orderHead中的userId = {}", orderHead.getUserId());
//                return;
//            }
//            //给上级的上级发佣金
//            Integer parentParentAmount = FormatUtils.amountToRateV2(orderHead.getSnapshotOriginTotalFee(), zeroParentRate.getParentParentRate());
//            userAccountOverviewService.addAmount(parentParentAmount, parentParentId, UserBillType.ZERO_PROFIT.value(), UserBillType.ZERO_PROFIT.desc(), UserInviteRelationTypeConstant.INVITE_ZERO);
//            //写入佣金通知
//            messageNotice(parentParentId, parentParentAmount, false);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//    /**
//     * vip佣金入账
//     *
//     * @param orderHead 订单
//     */
//    private void setCommission(OrderHead orderHead) {
//        try {
//            //卡对应酒店佣金入账（先查询该用户的会员卡对应的酒店账户id，再通过酒店账户id查询卡酒店佣金比率，最后入账）
//            AccountCardDTO accountCardDTO = memberCardService.selectOperatorIdAndCardNoByUserId(orderHead.getUserId(), MemberCardTypeEnum.VIP.value());
//            if (null == accountCardDTO || null == accountCardDTO.getCardNo()) {
//                log.info("查询到的酒店账户id或者订单对应卡号为空orderNo = {}", orderHead.getOrderNo());
//                return;
//            }
//            disposeCommission(orderHead, accountCardDTO.getAccountId(), accountCardDTO.getCardNo(), 1);
//            //非卡对应酒店佣金入账（先查询该用户的会员卡对应的酒店账户id，再通过酒店账户id查询卡酒店佣金比率，最后入账）
//            Integer noCardHotelAccountId = hotelInfoService.selectOperatorIdByHotelId(orderHead.getHotelId());
//            disposeCommission(orderHead, noCardHotelAccountId, accountCardDTO.getCardNo(), 2);
//            //卡商佣金入账(通过会员卡号查询卡商账户id)
////            MemberCard memberCard = memberCardService.selectByCardNo(accountCardDTO.getCardNo());
//            // 卡商为运营商服务商不分佣金
//            MemberCard memberCard = memberCardService.selectByCardNoAndType(accountCardDTO.getCardNo(), 2, 1);
//            if (null != memberCard && null != memberCard.getSalerId()) {
//                addCommission(orderHead, memberCard.getSalerId(), accountCardDTO.getCardNo(), VipCommissionBillTypeEnum.CARD_VIP.value());
//            }
//        } catch (ServiceException e) {
//            log.info("vip分佣异常订单号orderNo = {}", orderHead.getOrderNo());
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.error("vip分佣异常订单号orderNo = {}", orderHead.getOrderNo());
//        }
//    }
//
//    /**
//     * vip处理各类型佣金
//     *
//     * @param orderHead      处理的订单
//     * @param hotelAccountId 处理的酒店id
//     * @param cardNo         卡号
//     * @param type           1卡酒店，2非卡酒店
//     */
//    private void disposeCommission(OrderHead orderHead, Integer hotelAccountId, String cardNo, Integer type) {
//        if (1 == type) {
//            addCommission(orderHead, hotelAccountId, cardNo, VipCommissionBillTypeEnum.CARD_HOTEL.value());
//        } else {
//            addCommission(orderHead, hotelAccountId, cardNo, VipCommissionBillTypeEnum.NO_CARD_HOTEL.value());
//        }
//        //运营商佣金入账（先通过酒店账户id查询运营商账户id，再通过运营商账户id查询卡运营商佣金比率，最后入账）
//        HotelDeveloperRelation developerRelation = hotelDeveloperRelationService.selectByAccountIdAndType(hotelAccountId, HotelDeveloperRelationTypeEnum.OPERATOR.value(), 1);
//        if (null != developerRelation) {
//            if (1 == type) {
//                addCommission(orderHead, developerRelation.getDeveloperId(), cardNo, VipCommissionBillTypeEnum.CARD_OPERATOR.value());
//            } else {
//                addCommission(orderHead, developerRelation.getDeveloperId(), cardNo, VipCommissionBillTypeEnum.NO_CARD_OPERATOR.value());
//            }
//        } else {
//            //为空的话查询服务商
//            developerRelation = hotelDeveloperRelationService.selectByAccountIdAndType(hotelAccountId, HotelDeveloperRelationTypeEnum.SERVICE.value(), 1);
//            if (null != developerRelation) {
//                //给服务商发佣金
//                if (1 == type) {
//                    addCommission(orderHead, developerRelation.getDeveloperId(), cardNo, VipCommissionBillTypeEnum.CARD_SERVICE.value());
//                } else {
//                    addCommission(orderHead, developerRelation.getDeveloperId(), cardNo, VipCommissionBillTypeEnum.NO_CARD_SERVICE.value());
//                }
//                //给服务商上级发佣金(通过卡服务商id查询是否有上级运营商)
//                AccountVipSalerRelation relation = accountVipSalerRelationService.selectByAccountId(developerRelation.getDeveloperId(), 1);
//                //如果服务商有上级，给服务商上级发佣金
//                if (null != relation && null != relation.getParentId()) {
//                    if (1 == type) {
//                        addCommission(orderHead, relation.getParentId(), cardNo, VipCommissionBillTypeEnum.CARD_SERVICE_PARENT.value());
//                    } else {
//                        addCommission(orderHead, relation.getParentId(), cardNo, VipCommissionBillTypeEnum.NO_CARD_SERVICE_PARENT.value());
//                    }
//                }
//            }
//        }
//    }
//
//    /**
//     * vip发放佣金
//     *
//     * @param orderHead 处理的订单
//     * @param accountId 写入佣金的账户id
//     * @param cardNo    卡号
//     * @param type      分佣明细类型
//     */
//    private void addCommission(OrderHead orderHead, Integer accountId, String cardNo, Integer type) {
//        if (orderHead.getVipProfit() <= 0) {
//            vipCommissionBillService.vipOrderAdd(accountId, 0, orderHead.getOrderNo(), type, cardNo);
//        } else {
//            VipCommissionRateConfig hotelRateConfig = vipCommissionRateConfigService.selectByAccountIdAndType(accountId, type, 1);
//            if (null != hotelRateConfig) {
//                vipCommissionBillService.vipOrderAdd(accountId,
//                        FormatUtils.amountToRateV2(orderHead.getVipProfit(), hotelRateConfig.getRateValue()),
//                        orderHead.getOrderNo(), type, cardNo);
//            }
//        }
//    }
//
//    /**
//     * 写入上级佣金消息
//     *
//     * @param userId    用户id
//     * @param getAmount 金额
//     * @param isParent  是否是上级
//     */
//    private void messageNotice(Integer userId, Integer getAmount, Boolean isParent) {
//        String template;
//        Integer type;
//        if (isParent) {
//            template = MessageTemplate.ORDER_PARENT_COMMISSION;
//            type = MessageNotice.Type.order_parent_commission.value();
//        } else {
//            template = MessageTemplate.ORDER_TWO_PARENT_COMMISSION;
//            type = MessageNotice.Type.order_two_parent_commission.value();
//        }
//        try {
//            Map<String, Object> param = Maps.newHashMap();
//            param.put("getAmount", FormatUtils.fenToYuan(getAmount));
//            Map<String, String> map = messageNoticeTemplateService.commonValue(param, template);
//            messageNoticeService.activieyCreateAndSave(map, userId, type);
//        } catch (Exception e) {
//            log.error("30分钟订单取消异常{}", e.getLocalizedMessage());
//            e.printStackTrace();
//        }
//    }
//
//    /**
//     * 小vip佣金入账
//     *
//     * @param orderHead 订单
//     */
//    public void setMiniVipCommission(OrderHead orderHead) {
//        long time = System.currentTimeMillis();
//        log.info("小Vip佣金入账开始......");
//        try {
//            //1，查询出卡对应的酒店账户id和卡号
//            AccountCardDTO accountCardDTO = memberCardService.selectOperatorIdAndCardNoByUserId(orderHead.getUserId(), MemberCardTypeEnum.MINI_VIP.value());
//            if (null == accountCardDTO || null == accountCardDTO.getCardNo()) {
//                log.info("查询到的酒店账户id或者订单对应卡号为空orderNo = {}", orderHead.getOrderNo());
//                return;
//            }
//            miniDisposeCommission(orderHead, accountCardDTO.getAccountId(), accountCardDTO.getCardNo(), 1);
//            //2，通过订单中酒店账户查询酒店账户id
//            Integer noCardHotelAccountId = hotelInfoService.selectOperatorIdByHotelId(orderHead.getHotelId());
//            miniDisposeCommission(orderHead, noCardHotelAccountId, accountCardDTO.getCardNo(), 2);
//            //3，卡商为运营商服务商不分佣金
//            MemberCard memberCard = memberCardService.selectByCardNoAndType(accountCardDTO.getCardNo(), 2, 2);
//            if (null != memberCard && null != memberCard.getSalerId()) {
//                miniAddCommission(orderHead, memberCard.getSalerId(), accountCardDTO.getCardNo(), VipCommissionBillTypeEnum.CARD_VIP.value());
//            }
//        } catch (ServiceException e) {
//            log.info("小vip分佣异常订单号orderNo = {}", orderHead.getOrderNo());
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.error("小vip分佣异常订单号orderNo = {}", orderHead.getOrderNo());
//        }
//        log.info("小Vip佣金入账结束，总耗时{}毫秒", System.currentTimeMillis() - time);
//    }
//
//    /**
//     * 小vip处理各类型佣金
//     *
//     * @param orderHead      处理的订单
//     * @param hotelAccountId 处理的酒店id
//     * @param cardNo         卡号
//     * @param type           1卡酒店，2非卡酒店
//     */
//    private void miniDisposeCommission(OrderHead orderHead, Integer hotelAccountId, String cardNo, Integer type) {
//        //1，酒店佣金入账
//        if (1 == type) {
//            miniAddCommission(orderHead, hotelAccountId, cardNo, MiniVipCommissionBillTypeEnum.CARD_HOTEL.value());
//        } else {
//            miniAddCommission(orderHead, hotelAccountId, cardNo, MiniVipCommissionBillTypeEnum.NO_CARD_HOTEL.value());
//        }
//        //2，运营商佣金入账（先通过酒店账户id查询运营商账户id，再通过运营商账户id查询卡运营商佣金比率，最后入账）
//        HotelDeveloperRelation developerRelation = hotelDeveloperRelationService.selectByAccountIdAndType(hotelAccountId, HotelDeveloperRelationTypeEnum.OPERATOR.value(), 2);
//        if (null != developerRelation) {
//            if (1 == type) {
//                miniAddCommission(orderHead, developerRelation.getDeveloperId(), cardNo, MiniVipCommissionBillTypeEnum.CARD_OPERATOR.value());
//            } else {
//                miniAddCommission(orderHead, developerRelation.getDeveloperId(), cardNo, MiniVipCommissionBillTypeEnum.NO_CARD_OPERATOR.value());
//            }
//        } else {
//            //3，为空的话查询服务商
//            developerRelation = hotelDeveloperRelationService.selectByAccountIdAndType(hotelAccountId, HotelDeveloperRelationTypeEnum.SERVICE.value(), 2);
//            if (null != developerRelation) {
//                //4，给服务商发佣金
//                if (1 == type) {
//                    miniAddCommission(orderHead, developerRelation.getDeveloperId(), cardNo, MiniVipCommissionBillTypeEnum.CARD_SERVICE.value());
//                } else {
//                    miniAddCommission(orderHead, developerRelation.getDeveloperId(), cardNo, MiniVipCommissionBillTypeEnum.NO_CARD_SERVICE.value());
//                }
//                //5，查询服务商上级(通过卡服务商id查询是否有上级运营商)
//                AccountVipSalerRelation relation = accountVipSalerRelationService.selectByAccountId(developerRelation.getDeveloperId(), 2);
//                //6，如果服务商有上级，给服务商上级发佣金
//                if (null != relation && null != relation.getParentId()) {
//                    if (1 == type) {
//                        miniAddCommission(orderHead, relation.getParentId(), cardNo, MiniVipCommissionBillTypeEnum.CARD_SERVICE_PARENT.value());
//                    } else {
//                        miniAddCommission(orderHead, relation.getParentId(), cardNo, MiniVipCommissionBillTypeEnum.NO_CARD_SERVICE_PARENT.value());
//                    }
//                }
//            }
//        }
//    }
//
//    /**
//     * 小vip发放佣金
//     *
//     * @param orderHead 处理的订单
//     * @param accountId 写入佣金的账户id
//     * @param cardNo    卡号
//     * @param type      分佣明细类型
//     */
//    private void miniAddCommission(OrderHead orderHead, Integer accountId, String cardNo, Integer type) {
//        if (orderHead.getVipProfit() <= 0) {
//            miniVipCommissionBillService.orderAdd(accountId, 0, orderHead.getOrderNo(), type, cardNo);
//        } else {
//            Integer rate = getDefaultRate(type);
//            VipCommissionRateConfig hotelRateConfig = vipCommissionRateConfigService.selectByAccountIdAndType(accountId, type, 2);
//            if (null != hotelRateConfig) {
//                rate = hotelRateConfig.getRateValue();
//            }
//            miniVipCommissionBillService.orderAdd(accountId,
//                    FormatUtils.amountToRateV2(orderHead.getVipProfit(), rate), orderHead.getOrderNo(), type, cardNo);
//        }
//    }
//
//    /**
//     * 查询默认的佣金比率
//     *
//     * @param type
//     * @return
//     */
//    public Integer getDefaultRate(Integer type) {
//        //类型1:卡酒店 2:卡运营商 3:卡服务商 4:卡服务商上级 5:非卡酒店 6:非卡运营商 7:非卡服务商 8:非卡服务商上级 9:卡商
//        switch (type) {
//            case 1:
//            case 5:
//                return 2000;
//            case 2:
//            case 6:
//                return 750;
//            case 3:
//            case 7:
//                return 500;
//            case 4:
//            case 8:
//                return 250;
//            case 9:
//                return 300;
//            default:
//                return null;
//        }
//    }

}
